from django.db import models
from django.utils import timezone
from documents.models import Document

class ParsedQuestion(models.Model):
    """已解析的题目模型"""
    document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='parsed_questions', verbose_name='所属文档')
    content = models.TextField('题目内容')
    answer = models.TextField('参考答案', blank=True, null=True)
    detected_answer = models.CharField('检测到的答案', max_length=10, blank=True, null=True)
    page_number = models.IntegerField('页码', default=1)
    question_type = models.CharField('题目类型', max_length=50, blank=True, null=True)
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    
    class Meta:
        verbose_name = '解析题目'
        verbose_name_plural = verbose_name
        ordering = ['document', 'page_number', 'id']
    
    def __str__(self):
        return f"{self.document.title} - 第{self.page_number}页 - 题目{self.id}"

class ParserTask(models.Model):
    """解析任务模型，用于跟踪解析进度"""
    STATUS_CHOICES = (
        ('pending', '等待中'),
        ('processing', '处理中'),
        ('completed', '已完成'),
        ('failed', '失败'),
    )
    
    document = models.ForeignKey(Document, on_delete=models.CASCADE, related_name='parser_tasks', verbose_name='文档')
    status = models.CharField('状态', max_length=20, choices=STATUS_CHOICES, default='pending')
    created_at = models.DateTimeField('创建时间', default=timezone.now)
    completed_at = models.DateTimeField('完成时间', null=True, blank=True)
    questions_count = models.IntegerField('题目数量', default=0)
    error_message = models.TextField('错误信息', blank=True, null=True)
    auto_detect_answers = models.BooleanField('自动检测答案', default=True)
    
    class Meta:
        verbose_name = '解析任务'
        verbose_name_plural = verbose_name
        ordering = ['-created_at']
    
    def __str__(self):
        return f"{self.document.title} - {self.get_status_display()}"
